package com.zhl.media.app.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.birbit.android.jobqueue.JobManager;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.zhl.media.app.R;
import com.zhl.media.app.di.component.DaggerFileUploadComponent;
import com.zhl.media.app.di.module.FileUploadModule;
import com.zhl.media.app.event.Event;
import com.zhl.media.app.greendao.MediaPhotoDao;
import com.zhl.media.app.model.MediaPhoto;
import com.zhl.media.app.mvp.adapter.UploadGridViewAdapter;
import com.zhl.media.app.mvp.contract.FileUploadContract;
import com.zhl.media.app.mvp.presenter.FileUploadPresenter;
import com.zhl.media.app.thread.UploadJob;
import com.zhl.media.app.utils.EntityManager;
import com.zhl.media.app.utils.TaskJobManager;
import com.zhl.media.commonres.base.AppActivity;
import com.zhl.media.commonres.dialog.ConfirmDialog;
import com.zhl.media.commonres.dialog.ProgressDialog;
import com.zhl.media.commonres.view.EmptyLayout;
import com.zhl.media.commonres.view.PublicTitleBar;
import com.zhl.media.commonsdk.core.RouterHub;
import com.zhl.media.commonsdk.data.UserUtil;
import com.zhl.media.commonsdk.entity.MyPushPicture;
import com.zhl.media.commonsdk.utils.DeleteFileUtil;
import com.zhl.media.commonsdk.utils.EmptyUtils;
import org.simple.eventbus.Subscriber;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.zhl.media.app.mvp.model.api.Api.APP_DOMAIN;

@Route(path = RouterHub.APP_UPLOADACTIVITY)
public class FileUploadActivity extends AppActivity<FileUploadPresenter> implements FileUploadContract.View {
    @BindView(R.id.titleBar)
    PublicTitleBar titleBar;
    @BindView(R.id.gv)
    GridView gv;
    @BindView(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    private MediaPhotoDao mediaPhotoDao;
    private List<MediaPhoto> mediaPhotos;
    private UploadGridViewAdapter adapter;
    private ProgressDialog progressDialog;
    private PowerManager.WakeLock mWakeLock;
    private List<MediaPhoto> dscPhotos;
    private JobManager jobManager;
    private int count = 0;

    int c = 0;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerFileUploadComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .fileUploadModule(new FileUploadModule(this))
                .build()
                .inject(this);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 8:
                    int postion = (int)msg.obj;
                    count--;
                    if(count==0){
                        Event.postUpdateSkjg();
                        Event.postUpdateDscNum();
                        Event.postUpdateOffLineData();
                        titleBar.setRight("上传完成");
                        progressDialog.setComplete();
                        progressDialog.setMessage("上传完成");
                        progressDialog.setCloseText("关闭");
                    }else {
                        titleBar.setRight("剩余" + count + "张");
                        progressDialog.setMessage("上传中，" + dscPhotos.size() + "张，剩余" + count + "张，\n请不要关闭此窗口");
                    }
                    DeleteFileUtil.deleteFile(dscPhotos.get(postion).getPhotoPath());
                    mediaPhotoDao.delete(dscPhotos.get(postion));
                    break;
            }
        }
    };
    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_file_upload;
    }

    @SuppressLint("InvalidWakeLockTag")
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
        Intent i = getIntent();
        String getDate = i.getStringExtra("date");
        if (powerManager != null) {
            mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock");
        }
        jobManager = TaskJobManager.getInstance(this).getJobManager();
        progressDialog = new ProgressDialog(this,"上传进度");
        mediaPhotoDao = EntityManager.getInstance(this).getMediaPhotoDao();
        mediaPhotos = new ArrayList<>();
        dscPhotos = new ArrayList<>();
        mPresenter.currentPushImgList(getDate);
        adapter = new UploadGridViewAdapter(this,mediaPhotos);
        gv.setAdapter(adapter);
        titleBar.setTitle("上刊结果");
        titleBar.setImgLeft(R.drawable.public_ic_arrow_back_white_24dp, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(count == 0){
                    killMyself();
                }else {
                    ConfirmDialog confirmDialog = new ConfirmDialog(FileUploadActivity.this, "提示", "您正在上传，确定终止上传？", "取消", "确定");
                    confirmDialog.show();
                    confirmDialog.setListener(new ConfirmDialog.HallListener() {
                        @Override
                        public void confirm() {
                            new Thread(){
                                @Override
                                public void run() {
                                    jobManager.clear();
                                    killMyself();
                                }
                            }.start();
                        }
                    });
                }
            }
        });
        if (mediaPhotoDao.loadAll().size() > 0) {
            titleBar.setRight("上传", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(UserUtil.getAdjust()){
                        StyleableToast.makeText(FileUploadActivity.this, "请先上传调整结果", Toast.LENGTH_LONG, R.style.mytoast).show();
                        return;
                    }else {
                        count = dscPhotos.size();
                        titleBar.setRight("正在上传...", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                progressDialog.show();
                            }
                        });
                        progressDialog.show();
                        progressDialog.setCloseText("暂停上传");
                        for (int j = 0; j < dscPhotos.size(); j++) {
                            jobManager.addJobInBackground(new UploadJob(dscPhotos.get(j), j));
                        }
                        progressDialog.setListener(new ProgressDialog.HallListener() {
                            @Override
                            public void close() {
                                if(count==0){
                                    progressDialog.dismiss();
                                }else {
                                    c++;
                                    if(c%2==0){
                                        jobManager.start();
                                        progressDialog.setCloseText("暂停上传");
                                    }else {
                                        jobManager.stop();
                                        progressDialog.setCloseText("继续上传");
                                    }
                                }
                            }
                        });
                    }
                }
            });
        }
    }
    @Subscriber(tag = "upload_ok")
    public void uploadOk(int i) {
        Message msg = new Message();
        msg.what = 8;
        msg.obj = i;
        handler.sendMessage(msg);
    }

    @Override
    public void showLoading() {
    }
    @Override
    public void hideLoading() {
    }
    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }
    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }
    @Override
    public void killMyself() {
        finish();
    }
    @Override
    public void onSuccess(List<MyPushPicture> data) {
        this.mediaPhotos.clear();
        this.dscPhotos = mediaPhotoDao.loadAll();
//        for (int i = 0; i < 20; i++) {
//            this.mediaPhotos.add(mediaPhotoDao.loadAll().get(0));
//            this.dscPhotos.add(mediaPhotoDao.loadAll().get(0));
//        }
        this.mediaPhotos.addAll(dscPhotos);
        for (int i = 0; i < data.size(); i++) {
            MediaPhoto media = mediaPhotoDao.queryBuilder().where(MediaPhotoDao.Properties.MediaId.eq(data.get(i).getMediaId())).unique();
            MediaPhoto m = new MediaPhoto();
            m.setMediaId(data.get(i).getMediaId());
            m.setUploader(true);
            m.setPhotoPath(APP_DOMAIN + "file/downloadFile/"+data.get(i).getFileId());
            if(EmptyUtils.isEmpty(media) || EmptyUtils.isNotEmpty(data.get(i).getFileId())){
                this.mediaPhotos.add(m);
            }
        }
        if(this.mediaPhotos.size() == 0){
            emptyLayout.bindView(gv);
            emptyLayout.showEmpty("~暂无未上传数据~");
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mWakeLock != null) {
            mWakeLock.acquire();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWakeLock != null) {
            mWakeLock.release();
        }
    }

    @Override
    public void onBackPressed() {
        if(count == 0){
            killMyself();
        }else {
            ConfirmDialog confirmDialog = new ConfirmDialog(FileUploadActivity.this, "提示", "您正在上传，确定终止上传？", "取消", "确定");
            confirmDialog.show();
            confirmDialog.setListener(new ConfirmDialog.HallListener() {
                @Override
                public void confirm() {
                    new Thread(){
                        @Override
                        public void run() {
                            jobManager.clear();
                            killMyself();
                        }
                    }.start();
                }
            });
        }
    }

}
